﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.ComponentModel;

using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Domain;
using Top.Api.Util;

using System.Data;
using System.Data.SqlClient;


namespace TopApp.Library
{
    class GetInvalidOuterId : BackgroundWorker
    {
        private ITopClient client;
        private Properties.Settings settings;

        List<Item> invalidItems = new List<Item>();

        public GetInvalidOuterId()
        {
            settings = Properties.Settings.Default;

            client = new DefaultTopClient(settings.top_api_url, settings.top_app_key, settings.top_app_secret);

            this.WorkerReportsProgress = true;
            this.WorkerSupportsCancellation = true;

            this.DoWork += doIt;
        }

        private void doIt(object sender, DoWorkEventArgs e)
        {
            //开始工作

            ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
            req.Fields = "num_iid,outer_id,title";
            req.PageSize = 100L;
            req.PageNo = 1L;
            

            List<Item> items = new List<Item>();

            bool next_page = true;

            do{
                Thread.Sleep(500);
                this.ReportProgress(10,"正在获取第" + req.PageNo.ToString()+ "页");
                ItemsOnsaleGetResponse response = client.Execute(req, settings.top_session_key);
                if (response.IsError)
                {
                    this.CancelAsync();
                    return;
                }

                if (response.Items.Count > 0)
                {
                    items.AddRange(response.Items);
                    req.PageNo++;
                }
                else next_page =false;

            } while (next_page);

            for (int i = 0; i < items.Count; i++)
            {
                Thread.Sleep(500);
                items[i] = this.getFullTaobaoItem(items[i]);
            }

            foreach (Item item in items)
            {
                if (item.Skus.Count == 0)
                {
                    if (!this.checkKIS(item.OuterId,false)) this.invalidItems.Add(item);
                }
                else
                {
                    this.checkSkusKIS(item);
                }
            }

            this.ReportProgress(50, "共找到" + this.invalidItems.Count.ToString() + "项无效的淘宝商家编码");

            this.ReportProgress(100, this.invalidItems);

        }

        private bool checkKIS(string outerId,bool sku)
        {

            SqlConnection conn = new SqlConnection("Data Source=" + Properties.Settings.Default.kis_database_host + ";UID=" + Properties.Settings.Default.kis_database_user + ";PWD=" + Properties.Settings.Default.kis_database_pswd + ";Initial Catalog=" + Properties.Settings.Default.kis_database_name);

            SqlCommand comm = new SqlCommand("SELECT FFullNumber,FFullName FROM t_Item WHERE FFullNumber='" + outerId + "'", conn);
            conn.Open();
            SqlDataReader reader = comm.ExecuteReader();

            bool rt;
            string preString = "";
            if (sku) preString = "【sku】";

            if (outerId.Trim() == "")
            {
                this.ReportProgress(50, preString + "商家编码空缺！");
                return false;
            }

            if (reader.HasRows)
            {
                reader.Read();
                rt = true;
                this.ReportProgress(50, preString+"商家编码：" + outerId + "在金蝶中找到了货品" + reader["FFullName"].ToString());
            }
            else
            {
                rt = false;

                this.ReportProgress(50, preString+"商家编码：" + outerId + "在金蝶中找不到货品！");
            }

            reader.Close();
            conn.Close();
            conn.Dispose();

            return rt;

        }

        private void checkSkusKIS(Item item)
        {
            this.ReportProgress(50, "（SKU）商品【" + item.NumIid.ToString() + "】有"+item.Skus.Count.ToString()+"个SKU库存：");

            foreach (Sku sku in item.Skus)
            {
                if (!this.checkKIS(sku.OuterId, true)) this.invalidItems.Add(item);
            }
        }

        private Item getFullTaobaoItem(Item item)
        {
            this.ReportProgress(50,"正在获取商品【"+item.NumIid.ToString()+"】的详情");
            ItemGetRequest req = new ItemGetRequest();
            req.Fields = "num_iid,outer_id,title,sku";
            req.NumIid = item.NumIid;
            ItemGetResponse response = client.Execute(req, settings.top_session_key);
            return response.Item;
        }
    }
}
